import React, { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import "@/styles/tool/preview.scss";
import { Tabs, FloatButton, Button, message } from "antd";
import { CopyOutlined } from "@ant-design/icons";
import { CopyToClipboard } from "react-copy-to-clipboard";

import hljs from "highlight.js";
import "highlight.js/styles/github.css";
import { previewTable } from "@/api/tool/generate";

hljs.registerLanguage("java", require("highlight.js/lib/languages/java"));
hljs.registerLanguage("javascript", require("highlight.js/lib/languages/javascript"));

const GeneralComponent = () => {
  const [codeSource, setCodeSource] = useState([]);
  const { id: tableId } = useParams();

  useEffect(() => {
    previewTable(tableId).then((res) => {
      const data = Object.entries(res).map(([key, value]) => {
        const label = key.split("/").pop().replace(/\.vm/g, "");
        const language = label.split(".").pop();
        const { value: code } = hljs.highlight(value, { language }, true);
        const children = (
          <>
            <div className="button-card">
              <CopyToClipboard text={value} onCopy={() => message.success("复制成功")}>
                <Button type="default" size="small" icon={<CopyOutlined />} border="false">
                  复制
                </Button>
              </CopyToClipboard>
            </div>
            <pre dangerouslySetInnerHTML={{ __html: code }}></pre>
          </>
        );
        return { key, label, children };
      });
      setCodeSource(data);
    });
  }, [tableId]);

  return (
    <div className="preview-wrpper">
      <div className="header-card"></div>
      <div className="main-card">
        <Tabs
          items={codeSource}
          destroyInactiveTabPane={true}
          onChange={() => document.querySelector(".preview-wrpper .ant-tabs-content-holder").scrollTo(0, 0)}
        />
        <FloatButton.BackTop
          style={{ marginRight: "16px" }}
          target={() => document.querySelector(".preview-wrpper .ant-tabs-content-holder")}
        />
      </div>
      <div className="footer-card"></div>
    </div>
  );
};
export default GeneralComponent;
